package com.qf.nio.fileCopy;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Description:
 * @Author: xbb
 * @Date:2020/4/18
 */
public class FileCopyDemo {
    public static void main(String[] args) throws Exception {
        String path = "C:\\Users\\xbb\\Pictures\\Camera Roll\\1.jpg";

        //1.读取文件的一个Channel对象
        FileChannel ipsChannel = new FileInputStream(path).getChannel();

        //2.输出的Channel对象
        FileChannel opsChannel = new FileOutputStream("C:\\Users\\xbb\\Desktop\\x.jpg").getChannel();

        //3.ByteBuffer(底层是byte数组)
        ByteBuffer allocate = ByteBuffer.allocate(1024);    //创建一个缓冲区

        //4.读取数据到byteBuffer中
        while (ipsChannel.read(allocate)!=-1){

            allocate.flip();    //转化为可读模式

            //5.把ByteBuffer中的数据写入到管道中
            opsChannel.write(allocate);

            allocate.clear();   //清空缓冲区
        }

        //6.资源关闭
        ipsChannel.close();
        opsChannel.close();
    }
}
